package com.xjm.ips.controller.system;

import com.xjm.ips.entity.AjaxJson;
import com.xjm.ips.entity.Hr;
import com.xjm.ips.entity.Role;
import com.xjm.ips.service.HrService;
import com.xjm.ips.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/system/hr")
public class HrController {
    @Autowired
    HrService hrService;
    @Autowired
    RoleService roleService;

    @GetMapping("/")
    public List<Hr> getAllHrs(String keywords){
        return hrService.getAllHrs(keywords);
    }

    @GetMapping("/gethrinfo")
    public Hr getHrinfo(Authentication authentication){
        return ((Hr) authentication.getPrincipal());
    }

    @PutMapping("/updatehrinfo")
    public AjaxJson updateHrInfo(@RequestBody Hr hr,Authentication authentication){
        if(hrService.updateHr(hr)==1){
            //将更新后的Hr信息在内存中更新
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(hr,
                    authentication.getCredentials(),authentication.getAuthorities()));
            return AjaxJson.ok("更新个人信息成功！");
        }
        return AjaxJson.error("更新个人信息失败！");
    }

    @PutMapping("/")
    public AjaxJson updateHr(@RequestBody Hr hr){
        if(hrService.updateHr(hr)==1){
            return AjaxJson.ok("更新用户信息成功!");
        }
        return AjaxJson.error("更新用户信息失败!");

    }

    @GetMapping("/roles")
    public List<Role> getAllRoles(){
        return roleService.getAllRoles();
    }

    @PutMapping("/updatehrrole")
    public AjaxJson updateHrRole(Integer hrid,Integer[]rids){
        if(hrService.updateHrRole(hrid,rids)){
            return AjaxJson.ok("更新用户角色成功!");
        }
        return AjaxJson.error("更新用户角色失败!");
    }

    @DeleteMapping("/{id}")
    public AjaxJson deleteHrById(@PathVariable Integer id){
        if(hrService.deleteHrById(id)==1){
            return AjaxJson.ok("删除用户成功!");
        }
        return AjaxJson.error("删除用户失败");
    }

    @PostMapping("/")
    public AjaxJson addHr(@RequestBody Hr hr){
        if(hrService.addHr(hr)==1){
            return AjaxJson.ok("新增用户成功!");
        }
        return AjaxJson.error("新增用户失败!");
    }
}
